/**
 *---------------------------------------------------------------------------------------------------------------------
 *  @copyright Copyright (c) 2022  <dx_65535@163.com>.
 *
 *  @file       : main_unix_stream_client.cc
 *  @author     : Xiang.D (dx_65535@163.com)
 *  @version    : 1.0
 *  @brief      : Blog: https://mp.weixin.qq.com/s/eoCPWMGbIcZyxvJ3dMjQXQ
 *  @date       : 2024/11/22
 *
 *
 *  Change History:
 *  <Date>     | <Version> | <Author>       | <Description>
 *---------------------------------------------------------------------------------------------------------------------
 *  2024/11/24 | 1.0.0.1   | Xiang.D        | Create file
 *---------------------------------------------------------------------------------------------------------------------
 *
 */
#include <list>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "PSocket.h"
#include "EpollEventHandler.h"

using namespace std;

#define SPR_LOGD(fmt, args...) printf("MainUnStreamClient D: %4d " fmt, __LINE__, ##args)
#define SPR_LOGW(fmt, args...) printf("MainUnStreamClient W: %4d " fmt, __LINE__, ##args)
#define SPR_LOGE(fmt, args...) printf("MainUnStreamClient E: %4d " fmt, __LINE__, ##args)

int main(int argc, char *argv[])
{
    if (argc != 3) {
        SPR_LOGE("Usage: %s <srvPath> <cliPath>\n", argv[0]);
        return -1;
    }

    string srvPath = argv[1];
    string cliPath = argv[2];

    auto pUnStreamClient = make_shared<PUnixStreamClient>([&](size_t ret, string bytes, void* arg) {
        auto pTcpCli = reinterpret_cast<PUnixStreamClient*>(arg);
        if (!pTcpCli) {
            SPR_LOGE("pTcpCli is nullptr\n");
            return;
        }

        if (ret <= 0) {
            SPR_LOGD("read fail! ret = %ld (%s)\n", ret, strerror(errno));
            pTcpCli->Close();
            return;
        }

        sleep(2);   // 避免调试刷屏
        SPR_LOGD("# RECV [%d]> %s\n", pTcpCli->GetEvtFd(), bytes.c_str());
        std::string sBuf = "Hello, unix server";
        int32_t rc = pTcpCli->Write(sBuf);
        if (rc > 0) {
            SPR_LOGD("# SEND [%d]> %s\n", pTcpCli->GetEvtFd(), sBuf.c_str());
        }
    });

    auto epollHandler = EpollEventHandler::GetInstance();
    pUnStreamClient->AsUnixStreamClient(true, srvPath, cliPath);
    pUnStreamClient->Write("Hello, unix sever");
    epollHandler->EpollLoop();
    return 0;
}

